package awConnectionService;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import entities.User;

public class UserDB {
	private String dbName = "capstone";
	
	private Connection con = null;
	
	public UserDB(Connection con){
		this.con = con;
	}
	
	public User getUser(String username){
		System.out.println("UserDB: getUser()");
		User user = new User();
		user.setUsername("NOTFOUND");
		try {
			System.out.println(con);
			Statement stat = con.createStatement();
			stat.execute("USE " + dbName + ";");
			
			ResultSet rs = stat.executeQuery("SELECT * FROM users WHERE username = '" + username + "';");

			if(rs.next()){
				user.setId(rs.getString("user_id"));
				user.setUsername(rs.getString("username"));
				user.setFname(rs.getString("fname"));
				user.setLname(rs.getString("lname"));
				user.setEmail(rs.getString("email"));
				user.setPassword(rs.getString("password"));
				user.setRole(rs.getString("role"));
			}
			
		} catch (SQLException e) {e.printStackTrace();
		}
		
		return user;
	}
	
	public void addUser(User user){
		System.out.println("UserDB: addUser()");
		
		try{
			Statement stat = con.createStatement();
			stat.execute("USE " + dbName + ";");
			
			stat.executeUpdate("INSERT INTO users (username, password, email, fname, lname, role) VALUES('" + 
					user.getUsername() + "', '" + user.getPassword() + "', '" + user.getEmail() + "', '" +
					user.getFname() + "', '" + user.getLname() + "', '" + user.getRole() + "');");
			
			stat.close();
		}catch (SQLException ex){ex.printStackTrace();
		}
	}
	
	public void addUserdevice(String uuid, int id){
		System.out.println("UserDB: addUserdevice()");
		
		try{
			Statement stat = con.createStatement();
			stat.execute("USE " + dbName + ";");
			
			stat.executeUpdate("INSERT INTO userdevices (deviceuuid, userid) VALUE('" + uuid +"', '" + id +"');");
			
			stat.close();
		}catch(SQLException ex){ex.printStackTrace();}
		
	}

}
